package com.prawn.traceability.service;

import java.util.*;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.prawn.traceability.dao.*;
import com.prawn.traceability.pojo.*;
import entity.Base;
import com.prawn.traceability.pojo.Shrimp;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import util.IdWorker;

/**
 * 服务层
 *
 * @author Administrator
 */
@Service
public class AdultShrimpService {

    @Autowired
    private AdultShrimpDao adultShrimpDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private StorageDao storageDao;

    @Autowired
    private PlantDao plantDao;

    @Autowired
    private ShrimpDao shrimpDao;

    @Autowired
    private BaseDao baseDao;

    @Autowired
    private ShrimpFarmingDao shrimpFarmingDao;

    @Autowired
    private LogisticsDao logisticsDao;

    @Autowired
    private QualificationDao qualificationDao;

    @Autowired
    private MonitorClient monitorClient;

    @Resource
    private RedisTemplate<String, Map<String, Object>> redisTemplate;

    public Map<String, Object> traceability(String adultShrimpId) {
        Map<String, Object> map = new HashMap<>();
        //成虾信息
        AdultShrimp adultShrimp = adultShrimpDao.findById(adultShrimpId).get();
        map.put("adultShrimp", adultShrimp);
        //虾苗信息
        Shrimp shrimp = shrimpDao.findById(adultShrimp.getShrimpId()).get();
        map.put("shrimp", shrimp);
        //养殖基地信息
        Base base = baseDao.findById(adultShrimp.getBaseId()).get();
        map.put("base", base);
        //虾苗养殖信息
        List<ShrimpFarming> shrimpFarmings = shrimpFarmingDao.findByShrimpId(adultShrimp.getShrimpId());
        map.put("shrimpFarmings", shrimpFarmings);

        //监控
        Result monitorResult = monitorClient.getBaseMonitor(adultShrimp.getBaseId());
        map.put("monitorResult", monitorResult);

        Map<String, Object> old = redisTemplate.opsForValue().get("adultShrimp_" + adultShrimpId);
        if (old == null) {
            old = new HashMap<>();
            //获取成虾物流信息
            List<Logistics> logistics = logisticsDao.findByAdultShrimpId(adultShrimpId);
            if (logistics != null) {
                old.put("logistics", logistics);
            }
            //判断是否进入冷库，是：获取冷库信息
            String storageId = adultShrimp.getStorageId();
            if (storageId != null && !"".equals(storageId)) {
                Storage storage = storageDao.findById(storageId).get();
                old.put("storage", storage);
            }
            //判断是否加工，是：获取加工信息
            String plantId = adultShrimp.getPlantId();
            if (plantId != null && !"".equals(plantId)) {
                Plant plant = plantDao.findById(plantId).get();
                old.put("plant", plant);
            }

            redisTemplate.opsForValue().set("adultShrimp_" + adultShrimpId, old, 1, TimeUnit.MINUTES);
        }
        map.put("others", old);

        return map;
    }

    /**
     * 查询全部列表
     *
     * @return
     */
    public List<AdultShrimp> findAll() {
        return adultShrimpDao.findAll();
    }


    /**
     * 条件查询+分页
     *
     * @param whereMap
     * @param page
     * @param size
     * @return
     */
    public Page<AdultShrimp> findSearch(Map whereMap, int page, int size) {
        Specification<AdultShrimp> specification = createSpecification(whereMap);
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return adultShrimpDao.findAll(specification, pageRequest);
    }


    /**
     * 条件查询
     *
     * @param whereMap
     * @return
     */
    public List<AdultShrimp> findSearch(Map whereMap) {
        Specification<AdultShrimp> specification = createSpecification(whereMap);
        return adultShrimpDao.findAll(specification);
    }

    /**
     * 根据ID查询实体
     *
     * @param id
     * @return
     */
    public AdultShrimp findById(String id) {
        return adultShrimpDao.findById(id).get();
    }

    /**
     * 增加
     *
     * @param adultShrimp
     */
    public void add(AdultShrimp adultShrimp) {
        if (adultShrimp.getId() == null || "".equals(adultShrimp.getId())) {
            adultShrimp.setId(idWorker.nextId() + "");
        }
        adultShrimpDao.save(adultShrimp);
    }

    /**
     * 修改
     *
     * @param adultShrimp
     */
    public void update(AdultShrimp adultShrimp) {
        adultShrimpDao.save(adultShrimp);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void deleteById(String id) {
        adultShrimpDao.deleteById(id);
    }

    /**
     * 动态条件构建
     *
     * @param searchMap
     * @return
     */
    private Specification<AdultShrimp> createSpecification(Map searchMap) {

        return new Specification<AdultShrimp>() {

            @Override
            public Predicate toPredicate(Root<AdultShrimp> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                // 成虾编号
                if (searchMap.get("id") != null && !"".equals(searchMap.get("id"))) {
                    predicateList.add(cb.like(root.get("id").as(String.class), "%" + (String) searchMap.get("id") + "%"));
                }
                // 虾苗编号
                if (searchMap.get("shrimpId") != null && !"".equals(searchMap.get("shrimpId"))) {
                    predicateList.add(cb.like(root.get("shrimpId").as(String.class), "%" + (String) searchMap.get("shrimpId") + "%"));
                }
                // 基地编号
                if (searchMap.get("baseId") != null && !"".equals(searchMap.get("baseId"))) {
                    predicateList.add(cb.like(root.get("baseId").as(String.class), "%" + (String) searchMap.get("baseId") + "%"));
                }
                // 检验结果
                if (searchMap.get("shrimpQualityResult") != null && !"".equals(searchMap.get("shrimpQualityResult"))) {
                    predicateList.add(cb.like(root.get("shrimpQualityResult").as(String.class), "%" + (String) searchMap.get("shrimpQualityResult") + "%"));
                }
                // 检验机构
                if (searchMap.get("shrimpInspectionAgency") != null && !"".equals(searchMap.get("shrimpInspectionAgency"))) {
                    predicateList.add(cb.like(root.get("shrimpInspectionAgency").as(String.class), "%" + (String) searchMap.get("shrimpInspectionAgency") + "%"));
                }
                // 创建者
                if (searchMap.get("createBy") != null && !"".equals(searchMap.get("createBy"))) {
                    predicateList.add(cb.like(root.get("createBy").as(String.class), "%" + (String) searchMap.get("createBy") + "%"));
                }
                // 二维码url
                if (searchMap.get("qrCodeUrl") != null && !"".equals(searchMap.get("qrCodeUrl"))) {
                    predicateList.add(cb.like(root.get("qrCodeUrl").as(String.class), "%" + (String) searchMap.get("qrCodeUrl") + "%"));
                }

                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));

            }
        };

    }

}
